摘要:讲解R的基本操作知识,了解R的特点、资源获取方式,并掌握基本的程序编写
- R语言是什么
- R和Rstudio的界面和基本操作
- R数据分析的例子
- R的学习方式与资料
2017年10月10日
摘要:讲解R的基本操作知识,了解R的特点、资源获取方式,并掌握基本的程序编写
install.packages("tidyverse")library(tidyverse)改变默认语言(建议设定为英文)
etc\Rconsole文件,language = en.Renviron,LANGUAGE=en查询当前工作目录getwd() 改变默认工作目录 setwd("D:/work")
注意Mac与Windows电脑路径表达差异
呈现全球国家的预期寿命(life expectancy)和人均GDP(GDP per capita)之间的关系. Hans Rosling曾经做个一个TED演讲。我们只做一个年份的。
#library(dplyr)
library(gganimate)
library(ggplot2)
library(readr)
# gapminder <- read_tsv("gapminderDataFiveYear.tsv")
gapminder <- read.csv("https://stat.duke.edu/~mc301/data/gapminder.csv")
gapminder_plot <- ggplot(gapminder) +
aes(x = gdpPercap, y = lifeExp, colour = continent, size = pop,
frame = year) +
geom_point(alpha = 0.4) +
scale_x_log10()
# gapminder_plot
gganimate(gapminder_plot, convert='gm convert', filename = "gapminder-gganimate.gif")
if (!require(hrbrthemes)) install.packages('hrbrthemes')
if (!require(rvest)) install.packages('rvest')
library(tidyverse)
对两个网页做同样的事情
list(
Obama="http://m.rasmussenreports.com/public_content/politics/obama_administration/obama_approval_index_history",
Trump="http://m.rasmussenreports.com/public_content/politics/trump_administration/trump_approval_index_history"
) %>%
map_df(~{
read_html(.x) %>%
html_table() %>%
.[[1]] %>%
tbl_df() %>%
select(date=Date, approve=`Total Approve`, disapprove=`Total Disapprove`)
}, .id="who") -> ratings
data <- mutate_at(ratings,
c("approve", "disapprove"),
function(x) as.numeric(gsub("%", "", x,fixed=TRUE))/100) %>%
mutate(date = lubridate::dmy(date)) %>%
filter(!is.na(approve)) %>%
group_by(who) %>%
arrange(date) %>%
mutate(dnum = 1:n()) %>%
ungroup()
## Warning in (function (x) : NAs introduced by coercion
## Warning in (function (x) : NAs introduced by coercion
ggplot(data,aes(dnum, approve, color=who)) +
geom_hline(yintercept = 0.5, size=0.5) +
geom_point(size=0.25) +
scale_y_percent(limits=c(0,1)) +
scale_color_manual(name=NULL, values=c("Obama"="#313695", "Trump"="#a50026")) +
labs(x="Day in office", y="Approval Rating",
title="Presidential approval ratings from day 1 in office",
subtitle="Data was taken solely from Trump's favorite polling site (Ramussen)",
caption="Data Source: \nCode: rasmussenreports.com")
管道操作符 %>% 是dplyr中的函数. 将管道的上端的结果作为下一行命令的首个输入元素.
ggplot2 中的 + 符号可以不断给图形添加图层(layerin)
help.start() 打开帮助文档首页help("foo")或?foo 查看函数foo的帮助(引号可以省略)help.search("foo")或??foo 以foo为关键词搜索本地帮助文档example("foo") 函数foo的使用示例(引号可以省略)RSiteSearch("foo") 以foo为关键词搜索在线文档和邮件列表存档apropos("foo", mode="function") 列出名称中含有foo的所有可用函data() 列出当前已加载包中所含的所有可用示例数据集vignette() 列出当前已安装包中所有可用的vignette文档vignette("foo")为主题foo显示指定的vignette文档初学入门:
tidyverse风格入门:
进阶内容:
数据绘图:
参考手册:
高级编程:
To be continued